<script setup>
import { ref } from "vue";
import { Plus } from "@element-plus/icons-vue";

import {
  userMgrUpdateStatusService,
  userMgrAddService,
  userMgrUpdateService,
  roleMgrDoAssignListService,
  roleMgrDoAssignRoleService,
} from "@/api";
import { useUserStore } from "@/stores";

// 使用用户存储模块
const userInfo = useUserStore();
// 抽屉的可见性状态
const visibleDrawer = ref(false);
// 默认表单数据
const defaultForm = {
  id: "",
  username: "",
  password: "",
  name: "",
  headUrl: "http://101.33.249.134:9000/aiphoto-admin/logo.png",
  description: "",
  status: 0,
  createTime: "",
  updateTime: "",
  isDeleted: 1,
  roleList: null,
  checkList: [],
};
let roleCheckList = ref([
  { label: "管理员", value: 1 },
  { label: "普通用户", value: 2 },
]);

// 表单模型，用于数据绑定和操作
const formModel = ref({ ...defaultForm });

// 角色操作标志，用于区分功能
let roleOperation = ref(false);

// 表单规则
const rules = {
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      pattern: /^[^\u4e00-\u9fa5\s]{4,}$/,
      message: "请输入一个至少4个字符,不包含中文或空格的用户名。",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^\S{6,100}$/,
      message: "密码必须是6-15位的非空字符",
      trigger: "blur",
    },
  ],
  description: [{ required: true, message: "请输入描述", trigger: "blur" }],
};

// 预览图片路径
const imgUrl = ref("");
// const onUploadFile = (uploadFile) => {
//   imgUrl.value = URL.createObjectURL(uploadFile.raw);
//   formModel.value.cover_img = uploadFile.raw;
// };

// 打开抽屉函数------start
let titleDrawer = ref("编辑用户");
let loadingfrom = ref(false);
/**
 * 打开抽屉函数，根据传入的行数据和操作类型，决定是编辑、添加还是角色分配操作
 * @param {Object} row - 行数据
 * @param {String} operate - 操作类型
 */
const open = async (row, operate) => {
  console.log(row);
  visibleDrawer.value = true;
  loadingfrom.value = true;
  try {
    if (row.id && operate != "role") {
      console.log("编辑回显");
      formModel.value = row;
      roleOperation.value = false;
      titleDrawer.value = "编辑用户";
    }
    if (!row.id) {
      console.log("添加功能，不显示状态");
      roleOperation.value = true;
      formModel.value = { ...defaultForm };
      titleDrawer.value = "添加用户";
    }
    if (operate == "role") {
      formModel.value = row;
      let {
        data: { assginRoleList, allRolesList },
      } = await roleMgrDoAssignListService(row.id);
      roleCheckList = allRolesList.map((item) => {
        item.label = item.roleName;
        item.value = item.id;
        return item;
      });
      formModel.value.checkList = assginRoleList.map((item) => {
        return item.id;
      });
      console.log("分配角色功能,不显示状态");
      titleDrawer.value = "分配角色";
      roleOperation.value = true;
    }
  } catch (error) {
  } finally {
    loadingfrom.value = false;
  }
};
defineExpose({ open });
// 打开抽屉函数------end

// 添加或编辑操作-------start

let loadingAdd = ref(false); // 添加和编辑操作的加载状态

const formRef = ref(); // 表单引用，用于表单验证和提交

// 发送到父组件的成功事件
const emit = defineEmits(["success"]);
/**
 * 提交表单数据，根据是否有ID判断是进行编辑还是添加操作
 * @param {String} state - 表单状态（已发布或草稿）
 */
const onSubmit = async (state) => {
  await formRef.value.validate(); // 验证表单
  loadingAdd.value = true;
  try {
    if (formModel.value.id && !roleOperation.value) {
      console.log("编辑操作");
      // 将status转回1/0
      formModel.value.status = formModel.value.status == false ? 0 : 1;
      await userMgrUpdateService(formModel.value);
      ElMessage.success("编辑成功");
      visibleDrawer.value = false;
      emit("success", "edit");
    }

    if (!formModel.value.id && roleOperation.value) {
      // 添加请求
      let res = await userMgrAddService(formModel.value);
      console.log(res);
      ElMessage.success("添加成功");
      visibleDrawer.value = false;
      emit("success", "add");
    }
    if (formModel.value.id && roleOperation.value) {
      // 分配角色请求
      let DoAssignRole = {
        roleIdList: formModel.value.checkList,
        userId: formModel.value.id,
      };
      let res = await roleMgrDoAssignRoleService(DoAssignRole);
      console.log(res);
      ElMessage.success("分配成功");
      visibleDrawer.value = false;
      // emit("success", "role");
    }
  } catch (error) {
    // ElMessage.error(error)
    formModel.value.status = formModel.value.status == 0 ? false : true;
    console.log(error);
  } finally {
    loadingAdd.value = false;
  }
};
// 添加或编辑操作-------end

// 切换用户状态-----start
// 加载状态的ref对象，用于状态切换的动画
let loadingStatus = ref(false);

/**
 * 异步函数，用于处理用户状态更改
 * @param {Object} row - 包含行数据的对象，此对象应包含状态和ID属性
 * @returns {Promise}
 */
const onStatusChange = async () => {
  try {
    loadingStatus.value = true;
    // 根据当前行的状态，重新转回1、0
    let status = formModel.value.status == false ? 0 : 1;
    await userMgrUpdateStatusService(formModel.value.id, status);
    ElMessage.success("修改成功");
  } catch (error) {
    row.status = !row.status;
    ElMessage.error("修改失败");
  } finally {
    loadingStatus.value = false;
  }
};
// 切换用户状态-----end
</script>

<template>
  <!-- 抽屉组件，用于编辑和添加用户 -->
  <el-drawer
    v-model="visibleDrawer"
    :title="titleDrawer"
    direction="rtl"
    size="60%"
    style="padding: 30px"
  >
    <!-- 表单组件，用于输入用户信息 -->
    <el-form
      :model="formModel"
      ref="formRef"
      :rules="rules"
      label-width="100px"
      label-position="top"
      style="width: 50%"
      v-loading="loadingfrom"
    >
      <el-form-item label="昵称" prop="name">
        <el-input
          v-model="formModel.name"
          placeholder="请输入昵称"
          :disabled="formModel.id != '' && roleOperation"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="formModel.username"
          placeholder="请输入用户名"
          :disabled="formModel.id != '' && roleOperation"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          show-password
          v-model="formModel.password"
          :disabled="!formModel.id == ''"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formModel.description"
          placeholder="请输入描述"
          :disabled="formModel.id != '' && roleOperation"
        ></el-input>
      </el-form-item>

      <el-form-item
        label="角色分配"
        prop="checkList"
        v-if="formModel.id && roleOperation"
      >
        <el-checkbox-group v-model="formModel.checkList">
          <el-checkbox
            v-for="item in roleCheckList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-checkbox-group>
      </el-form-item>

      <!-- 用户状态切换开关，仅在编辑操作时显示 -->
      <el-form-item label="状态" prop="status" v-if="!roleOperation">
        <el-switch
          v-model="formModel.status"
          :loading="loadingStatus"
          :disabled="formModel.id == userInfo.user.id"
          @change="onStatusChange()"
        />
      </el-form-item>

      <!-- 提交表单按钮 -->
      <el-form-item>
        <el-button
          type="primary"
          :icon="Plus"
          :loading="loadingAdd"
          @click="onSubmit('已发布')"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.el-input {
  max-width: 500px;
}
</style>
